<?php
// +----------------------------------------------------------------------
// | 知识星球[基于ThinkPHP5开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2019 abcblockchain.io
// +----------------------------------------------------------------------
// | 后台管理使用了HisiPHP
// +----------------------------------------------------------------------
// | Author: abcblockchain.io
// +----------------------------------------------------------------------
namespace app\common\model;

use think\Model;
use think\Db;
use app\common\model\Users;
use app\common\model\Message as msgModel;
use app\common\model\UsersCurrency as usersCurrencyModel;
use app\common\model\CurrencyLog as currencyLogModel;
use app\common\model\Currency as currencyModel;

/**
 * 星球模型
 * @package app\common\model
 */
class Group extends Model
{
    // 定义时间戳字段名
    protected $createTime = 'ctime';
    protected $updateTime = false;

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;


    /**
     * 创建星球
     * @param array $data
     * @author jyx
     * @return stirng|array
     */
    public function createGroup($data = [], $login = true)
    {
        $currencyModel = new currencyModel();
        $currencyId = $currencyModel->createCurrency($data['token_name'], $data['token_num']);
        if ($currencyId) {
            $map = [];
            $map['name'] = $data['name'];
            $map['user_id'] = $data['user_id'];
            $map['cover_pic'] = isset($data['cover_pic']) ? $data['cover_pic'] : '';
            $map['category_id'] = $data['category_id'];
            $map['mode'] = $data['mode'];
            $map['time_type'] = $data['time_type'];
            $map['currency_id'] = $currencyId;
            $map['token_num'] = $data['token_num'];
            $map['token_name'] = $data['token_name'];
            $map['group_no'] = $this->getGroupNo();
            if ($data['mode'] == 'pay') {
                $map['money'] = $data['money'];
            } else {
                $map['money'] = 0;
            }
            $map['summary'] = $data['summary'];

            $res = $this->validate('Group.create')->isUpdate(false)->save($map);
            $groupId = $this->getLastInsID();
            if (!$res) {
                return false;
            } else {
                $this->insertGroupUser($groupId, $data['user_id'], '', 'create', 0, 1, 3);
                $msgModel = new msgModel();
                $msgModel->createMsg($data['user_id'], 1, 0, '', $groupId);
                return true;
            }
        } else {
            return false;
        }
    }

    //关联用户表
    public function hasUser()
    {
        return $this->hasOne('Users', 'id', 'user_id');
    }

    //关联分类表
    public function hasCategories()
    {
        return $this->hasOne('GroupCategories', 'id', 'category_id');
    }

    /**
     * 星球详情
     * @author
     * @param $groupId
     */
    public function groupInfo($groupId)
    {
        $map['g.id'] = $groupId;
        $groupInfo = $this->alias('g')->join('users u', 'u.id=g.user_id')->join('group_categories gc', 'gc.id=g.category_id')->field('g.id,g.group_no,g.name,g.cover_pic,g.currency_id,g.user_id,g.mode,g.posts_count,g.users_count,g.money,g.summary,u.nick,u.avatar,gc.name as cate_name,g.ctime,u.last_login_time')->where($map)->find();
        return $groupInfo;
    }

    /**
     * 星球列表
     * @author
     * @param int $startNo
     * @param int $limit
     * @param string $type
     */
    public function groupList($startNo = 0, $limit = 6, $type = 0)
    {
        $map['status'] = 1;
        $map['audit'] = 1;
        if ($type == 1) {
            $map['is_hot'] = 1;
        } elseif ($type == 2) {
            $map['is_recommend'] = 1;
        }
        $startNo = $startNo * $limit;
        $groupList = $this->where($map)->field('id,group_no,name,cover_pic,posts_count,money')->limit($startNo, $limit)->order('id desc')->select();

        return $groupList;
    }

    /**
     * 星球会员
     * @author
     * @param $groupId
     * @param $userId
     * @return array|bool|false|\PDOStatement|string|Model
     */
    public function groupUser($groupId, $userId)
    {
        $map['user_id'] = $userId;
        $map['group_id'] = $groupId;
        $map['audit'] = 1;
        $map['disabled'] = 1;
        $map['status'] = 1;
        $groupUser = Db::name('group_members')->where($map)->find();
        if ($groupUser) {
            return $groupUser;
        } else {
            return false;
        }
    }

    /**
     * 加入星球
     * @author
     * @param $groupId
     * @param $userId
     * @param int $audit
     * @param int $role
     * @return bool|int|string
     */
    public function insertGroupUser($groupId, $userId, $tradepwd = '', $type = '', $currencyId = 0, $audit = 1, $role = 0)
    {
        if ($groupId > 0 && $userId > 0) {
            $usersModel = new Users();
            $currencyModel = new currencyModel();
            $usersCurrency = new usersCurrencyModel();
            $groupInfo = $this->groupInfo($groupId);
            if (!$groupInfo) {
                return false;
            }
            if($currencyId == 2){
                $currencyInfo = $currencyModel->currencyInfo($currencyId);
                $needMoney = round($groupInfo['money'] / $currencyInfo['last_price'],2);
            }else{
                $needMoney = $groupInfo['money'];
            }
            $userInfo = $usersModel->usersInfo($userId);
            if (!$userInfo) {
                return false;
            }
            $groupUser = $this->groupUser($groupId, $userId);
            if ($groupUser) {
                return false;
            } else {
                if ($type != 'create') {
                    $userNum = $usersCurrency->getUserTokenNum($userId, $currencyId);
                    if ($needMoney > $userNum) {
                        return -1;
                        exit();
                    }
                    if ($needMoney > 0) {
                        if (!password_verify($tradepwd, $userInfo['tradepwd'])) {
                            //$this->error = '支付密码错误！';
                            return -2;
                            exit();
                        }
                    }
                }
                $data['group_id'] = $groupId;
                $data['user_id'] = $userId;
                $data['audit'] = $audit;
                $data['role'] = $role;
                Db::startTrans();
                try {
                    $usersCurrency->createUsersCurrency($userId,$groupInfo['currency_id']);
                    $addGroup = Db::name('group_members')->insert($data);
                    $this->where('id', $groupId)->setInc('users_count');
                    //操作用户账户
                    if ($type != 'create') {
                        $tokenPrice = Db::name('currency')->field('last_price')->where('id',$groupInfo['currency_id'])->find();
                        if($currencyId == 1){
                            $vnsPrice = Db::name('currency')->field('last_price')->where('id',2)->find();
                            $getToken = $needMoney / $vnsPrice['last_price'] / $tokenPrice['last_price'];
                        }else{
                            $getToken = $needMoney / $tokenPrice['last_price'];
                        }
                        $costArr = [];
                        $costArr['uid'] = $userId;
                        $costArr['currency_id'] = $currencyId;
                        $costArr['number'] = $needMoney;
                        $costArr['opt_type'] = 6;
                        $costArr['status'] = 2;
                        $costArr['ctime'] = time();
                        $costArr['group_id'] = $groupId;
                        $costArr['in_uid'] = $userId;
                        Db::name('exchange')->insert($costArr);
                        $getToken = floor($getToken*10000)/10000;
                        $res = $usersCurrency->changeUserNum($getToken,1,$groupInfo['currency_id'],$userId);
                        $getArr = [];
                        $getArr['uid'] = $userId;
                        $getArr['currency_id'] = $groupInfo['currency_id'];
                        $getArr['number'] = $getToken;
                        $getArr['opt_type'] = 7;
                        $getArr['status'] = 2;
                        $getArr['ctime'] = time();
                        $getArr['group_id'] = $groupId;
                        $getArr['in_uid'] = $userId;
                        Db::name('exchange')->insert($getArr);
                        $currencyLog = new currencyLogModel();
                        $userNum = $usersCurrency->changeUserNum($needMoney, 2, $currencyId, $userId);
                        $userLog = $currencyLog->insertCurrencyLog($userId, $currencyId, $needMoney, 1, 2);
                        if ($addGroup === false || $userNum === false || $userLog === false) {
                            Db::rollback();
                            return false;
                        } else {
                            Db::commit();
                            return 1;
                        }
                    } else {
                        if ($addGroup) {
                            Db::commit();
                            return 1;
                        } else {
                            Db::rollback();
                            return false;
                        }
                    }

                } catch (\Exception $e) {
                    dump($e);
                    Db::rollback();
                    return false;
                }
            }

        } else {
            return false;
        }
    }

    /**
     * 编辑星球会员相关
     * @author
     * @param $groupId
     * @param $userId
     * @param $optionType
     * @param $value
     */
    public function editGoupUser($groupId, $userId, $field, $value)
    {
        if ($groupId > 0 && $userId > 0) {
            $map['group_id'] = $groupId;
            $map['user_id'] = $userId;
            $data[$field] = $value;
            $res = Db::table('group_members')->where($map)->update($data);
            if ($res !== false) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }

    }

    /**
     * 我的星球
     * @author
     * @param $userId
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function myGroup($userId,$startNo = 0, $limit = 6)
    {
        $map['gm.user_id'] = $userId;
        $map['gm.audit'] = 1;
        $map['g.audit'] = 1;
        $map['gm.disabled'] = 1;
        $map['gm.status'] = 1;
        $startNo = $startNo * $limit;
        $myGroup = Db::name('group_members')->alias('gm')->join('group g', 'gm.group_id = g.id')->field('gm.group_id,g.cover_pic,g.name,g.summary,g.users_count')->where($map)->limit($startNo, $limit)->select();
        return $myGroup;
    }

    /**
     * 我创建的班级
     * @author
     * @param $userId
     * @param int $startNo
     * @param int $limit
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function myCreate($userId,$startNo = 0, $limit = 6)
    {
        $map['user_id'] = $userId;
        $map['status'] = 1;
        //$map['audit'] = 1;
        $startNo = $startNo * $limit;
        $myGroup = $this->field('id as group_id,cover_pic,name,summary,users_count,audit')->where($map)->limit($startNo, $limit)->select();
        return $myGroup;
    }

    /**
     * 获取我的星球ID
     * @author
     * @param $userId
     * @return string
     */
    public function getUserGroup($userId)
    {
        $map['user_id'] = $userId;
        $map['audit'] = 1;
        $map['disabled'] = 1;
        $map['status'] = 1;
        $userGroup = Db::name('group_members')->field('group_id')->where($map)->select();
        $myGroupStr = '';
        foreach ($userGroup as $k => $v) {
            $myGroupStr .= $v['group_id'] . ",";
        }
        return $myGroupStr;
    }

    /**
     * 搜索星球
     * @author
     * @param $key
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function searchGroup($key, $userGroup = '', $type = 0, $startNo = 0, $limit = 6)
    {
        $mapName['g.name'] = array('like', "%$key%");
        $mapGroupNo['g.group_no'] = $key;
        $mapGroupNo['g.status'] = 1;
        $mapGroupNo['g.audit'] = 1;
        $mapName['g.status'] = 1;
        $mapName['g.audit'] = 1;
        if ($type == 0) {
            $mapName['g.id'] = array('in', $userGroup);
            $mapGroupNo['g.id'] = array('in', $userGroup);
        } else {
            $mapName['g.id'] = array('not in', $userGroup);
            $mapGroupNo['g.id'] = array('not in', $userGroup);
        }
        $searchRes = $this->alias('g')->join('users u', 'g.user_id=u.id')->where(function ($query) use ($mapName) {
            $query->where($mapName);
        })->whereOr(function ($query) use ($mapGroupNo) {
            $query->where($mapGroupNo);
        })->field('g.name,g.id,g.group_no,g.cover_pic,g.summary,g.users_count,g.posts_count,u.nick')->limit($startNo, $limit)->select();
        return $searchRes;
    }

    /**
     * 获取班级NO
     * @author
     * @return int
     */
    public function getGroupNo()
    {
        $groupNo = rand(10000000, 99999999);
        $map['group_no'] = $groupNo;
        $isHave = $this->where($map)->field('id')->find();
        if ($isHave) {
            $groupNo = $this->getGroupNo();
            return $groupNo;
        } else {
            return $groupNo;
        }
    }

    /**
     * 获取班级成员列表
     * @author
     * @param $groupId
     * @param int $startNo
     * @param int $limit
     * @return array|false|mixed|\PDOStatement|string|\think\Collection
     */
    public function getMemberList($groupId ,$startNo = 0, $limit = 6){
        $map['gm.group_id'] = $groupId;
        $map['gm.audit'] = 1;
        $map['gm.disabled'] = 1;
        $map['gm.status'] = 1;
        $startNo = $startNo * $limit;
        $memberList = Db::name('group_members')->alias('gm')->join('users u', 'gm.user_id = u.id')->field('gm.group_id,gm.user_id,gm.role,u.nick,u.avatar')->where($map)->limit($startNo, $limit)->select();
        return $memberList ? $memberList : array();
    }

    /**
     * 退出班级
     * @author
     * @param $groupId
     * @param $userId
     * @return int
     */
    public function quitGroup($groupId,$userId){
        $map['group_id'] = $groupId;
        $map['user_id'] = $userId;
        $map['status'] = 1;
        $map['disabled'] = 1;
        $groupUserInfo = Db::name('group_members')->where($map)->field('id,role')->find();
        if($groupUserInfo){
            if($groupUserInfo['role'] == 3){
                return -1;
            }else{
                $saveData['status'] = 0;
                $saveData['disabled'] = 0;
                $upRes = Db::name('group_members')->where($map)->update($saveData);
                if($upRes){
                    $this->where('id',$groupId)->setDec('users_count');
                    return 1;
                }else{
                    return 0;
                }
            }
        }else{
            return 0;
        }


    }

}
